package org.shoukaiseki.aqoeous.config;

import org.shoukaiseki.aqoeous.exception.ResultException;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import javax.annotation.Resource;
import java.util.List;

/**
 * <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  18-12-4 下午5:09<br>
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
@Configuration
public class ValidatorConfigure implements Validator {

    @Resource
    org.springframework.validation.Validator validator;


    @Override
    public void validate(Object target, BindingResult bindingResult) {
        validate(target,bindingResult,false);
    }


    @Override
    public void validate(Object target, BindingResult bindingResult, boolean showObjectname) {
        validator.validate(target,bindingResult);

        if(bindingResult.hasErrors()){

            List<ObjectError> allErrors = bindingResult.getAllErrors();
            StringBuilder sb = new StringBuilder();
            for (ObjectError objectError : allErrors) {

                if(showObjectname){
                    sb.append(bindingResult.getObjectName()).append(".");
                }
                if(objectError instanceof FieldError){
                    sb.append(((FieldError) objectError).getField()).append(";");
                }else{

                    sb.append(objectError.getArguments() ).append(";");
                }
            }
            //验证出现错误,此处抛出异常
            throw new ResultException("验证失败{0}").format(sb);
        }

    }
}

